unit ucNetworkPlay;

interface

uses
  System.Drawing, System.Collections, System.ComponentModel,
  System.Windows.Forms, System.Data, System.Net, System.Net.Sockets,
  Settings, System.Threading, System.Text, MultiplayerPlayer,
  System.Xml;

type
  TucNetworkPlay = class(System.Windows.Forms.UserControl)
  {$REGION 'Designer Managed Code'}
  strict private
    /// <summary>
    /// Required designer variable.
    /// </summary>
    components: System.ComponentModel.IContainer;
    Label1: System.Windows.Forms.Label;
    txtName: System.Windows.Forms.TextBox;
    btnSetName: System.Windows.Forms.Button;
    lstPlayers: System.Windows.Forms.ListBox;
    btnChallenge: System.Windows.Forms.Button;
    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    procedure InitializeComponent;
    procedure TucNetworkPlay_Load(sender: System.Object; e: System.EventArgs);
    procedure btnSetName_Click(sender: System.Object; e: System.EventArgs);
    procedure btnChallenge_Click(sender: System.Object; e: System.EventArgs);
  {$ENDREGION}
  strict protected
    /// <summary>
    /// Clean up any resources being used.
    /// </summary>
    procedure Dispose(Disposing: Boolean); override;
  private
    player : TMultiplayerPlayer;

    procedure UpdateOrAddPlayer(p : TMultiplayerPlayer);
    procedure DoUpdate();
  public
    constructor Create;
  end;

  [assembly: RuntimeRequiredAttribute(TypeOf(TucNetworkPlay))]

implementation

uses
  System.Globalization;

{$AUTOBOX ON}

{$REGION 'Windows Form Designer generated code'}
/// <summary>
/// Required method for Designer support -- do not modify
/// the contents of this method with the code editor.
/// </summary>
procedure TucNetworkPlay.InitializeComponent;
begin
  Self.Label1 := System.Windows.Forms.Label.Create;
  Self.txtName := System.Windows.Forms.TextBox.Create;
  Self.btnSetName := System.Windows.Forms.Button.Create;
  Self.lstPlayers := System.Windows.Forms.ListBox.Create;
  Self.btnChallenge := System.Windows.Forms.Button.Create;
  Self.SuspendLayout;
  // 
  // Label1
  // 
  Self.Label1.Font := System.Drawing.Font.Create('Kristen ITC', 8.25, System.Drawing.FontStyle.Regular, 
      System.Drawing.GraphicsUnit.Point, (Byte(0)));
  Self.Label1.ForeColor := System.Drawing.Color.Goldenrod;
  Self.Label1.Location := System.Drawing.Point.Create(8, 8);
  Self.Label1.Name := 'Label1';
  Self.Label1.Size := System.Drawing.Size.Create(80, 24);
  Self.Label1.TabIndex := 0;
  Self.Label1.Text := 'Your name:';
  // 
  // txtName
  // 
  Self.txtName.Location := System.Drawing.Point.Create(88, 8);
  Self.txtName.Name := 'txtName';
  Self.txtName.Size := System.Drawing.Size.Create(288, 22);
  Self.txtName.TabIndex := 1;
  Self.txtName.Text := 'Unnamed';
  // 
  // btnSetName
  // 
  Self.btnSetName.ForeColor := System.Drawing.Color.Goldenrod;
  Self.btnSetName.Location := System.Drawing.Point.Create(384, 8);
  Self.btnSetName.Name := 'btnSetName';
  Self.btnSetName.TabIndex := 2;
  Self.btnSetName.Text := 'Set name';
  Include(Self.btnSetName.Click, Self.btnSetName_Click);
  // 
  // lstPlayers
  // 
  Self.lstPlayers.ItemHeight := 16;
  Self.lstPlayers.Location := System.Drawing.Point.Create(8, 40);
  Self.lstPlayers.Name := 'lstPlayers';
  Self.lstPlayers.Size := System.Drawing.Size.Create(184, 324);
  Self.lstPlayers.TabIndex := 3;
  // 
  // btnChallenge
  // 
  Self.btnChallenge.ForeColor := System.Drawing.Color.Goldenrod;
  Self.btnChallenge.Location := System.Drawing.Point.Create(8, 376);
  Self.btnChallenge.Name := 'btnChallenge';
  Self.btnChallenge.Size := System.Drawing.Size.Create(184, 23);
  Self.btnChallenge.TabIndex := 4;
  Self.btnChallenge.Text := 'Challenge!';
  Include(Self.btnChallenge.Click, Self.btnChallenge_Click);
  // 
  // TucNetworkPlay
  // 
  Self.Controls.Add(Self.btnChallenge);
  Self.Controls.Add(Self.lstPlayers);
  Self.Controls.Add(Self.btnSetName);
  Self.Controls.Add(Self.txtName);
  Self.Controls.Add(Self.Label1);
  Self.Font := System.Drawing.Font.Create('Kristen ITC', 8.25, System.Drawing.FontStyle.Regular, 
      System.Drawing.GraphicsUnit.Point, (Byte(0)));
  Self.Name := 'TucNetworkPlay';
  Self.Size := System.Drawing.Size.Create(487, 573);
  Include(Self.Load, Self.TucNetworkPlay_Load);
  Self.ResumeLayout(False);
end;
{$ENDREGION}

constructor TucNetworkPlay.Create;
var
  updateThread : Thread;
  
begin
  inherited Create;
  //
  // Required for Windows Form Designer support
  //
  InitializeComponent;
  //
  // TODO: Add any constructor code after InitializeComponent call
  //

  self.player := TMultiplayerPlayer.Create(txtName.Text);
  
  updateThread := Thread.Create(DoUpdate);
  updateThread.Start();
end;

procedure TucNetworkPlay.btnChallenge_Click(sender: System.Object; e: System.EventArgs);
var
  wc : WebClient;
  cp : TMultiplayerPlayer;

begin
  if not (self.lstPlayers.SelectedItem = nil) then
  begin
    cp := self.lstPlayers.SelectedItem as TMultiPlayerPlayer;

    if (cp.Id = self.player.Id) then
    begin
      MessageBox.Show('You cannot challenge yourself!');
    end
    else
    begin
      wc := WebClient.Create();
      wc.DownloadData(TSettings.MultiplayerUrl + '?action=sendRequest&from=' + player.Id.ToString() + '&to=' + cp.Id.ToString());
      MessageBox.Show(cp.Name + ' has been challenged!');
    end;
  end;
end;

procedure TucNetworkPlay.btnSetName_Click(sender: System.Object; e: System.EventArgs);
begin
  self.player.Name := txtName.Text;
end;

procedure TucNetworkPlay.DoUpdate();
var
  xdoc : XmlDocument;
  wc : WebClient;
  response : String;
  tempNode : XmlNode;
  tempNodeList : XmlNodeList;
  i, x : Integer;
  p, p2 : TMultiplayerPlayer;
  arr : ArrayList;
  remove : Boolean;

begin
  while True do
  begin
    arr := ArrayList.Create();
    xdoc := XmlDocument.Create();
    wc := WebClient.Create();
    response := wc.DownloadData(TSettings.MultiplayerUrl + '?action=updatePlayer&name=' + self.Player.Name + '&guid=' + self.Player.Uid);

    xdoc.LoadXml(response);
    tempNode := xdoc.GetElementsByTagName('key')[0];
    self.player.Id := Int32.Parse(tempNode.FirstChild.Value);

    tempNodeList := xdoc.GetElementsByTagName('player');

    for i := 0 to tempNodeList.Count - 1 do
    begin
      tempNode := tempNodeList[i];
      p :=
        TMultiplayerPlayer.Create(
          tempNode.Attributes['name'].Value,
          Int32.Parse(tempNode.Attributes['id'].Value)
      );

      self.UpdateOrAddPlayer(p);
      arr.Add(p);
    end;

    //
    // remove others
    for i := 0 to self.lstPlayers.Items.Count - 1 do
    begin
      p := self.lstPlayers.Items[i] as TMultiplayerPlayer;
      remove := true;

      for x := 0 to arr.Count - 1 do
      begin
        p2 := arr[x] as TMultiplayerPlayer;

        if (p2.Id = p.Id) then
        begin
          remove := false;
          break;
        end;
      end;

      if (remove) then
        self.lstPlayers.Items.RemoveAt(i);
    end;

    self.lstPlayers.Invalidate();

    tempNodeList := xdoc.GetElementsByTagName('request');
    for i := 0 to tempNodeList.Count - 1 do
    begin
      tempNode := tempNodeList[i];
      MessageBox.Show(System.String.Format('You have been challenged by {0}', tempNode.Attributes['from'].Value));
    end;

    System.Threading.Thread.Sleep(1000);
  end;
end;

procedure TucNetworkPlay.UpdateOrAddPlayer(p: TMultiplayerPlayer);
var
  p2 : TMultiplayerPlayer;
  i : Integer;
  found : Boolean;
begin
  found := false;
  
  for i := 0 to lstPlayers.Items.Count - 1 do
  begin
    p2 := lstPlayers.Items[i] as TMultiplayerPlayer;
    if (p2.Id = p.Id) then
    begin
      p2.Name := p.Name;
      found := true;

      lstPlayers.Items[i] := p2;
      break;
    end;
  end;

  if not found then
  begin
    lstPlayers.Items.Add(p);
  end;
end;

procedure TucNetworkPlay.TucNetworkPlay_Load(sender: System.Object; e: System.EventArgs);
begin

end;

procedure TucNetworkPlay.Dispose(Disposing: Boolean);
begin
  if Disposing then
  begin
    if Components <> nil then
      Components.Dispose();
  end;
  inherited Dispose(Disposing);
end;

end.
